package com.shiro.utils;

import com.shiro.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * 密码工具类
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
public class PasswordHelper {

	/**随机数生成器*/
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    /**采用md5算法*/
    private String algorithmName = "md5";
    
    /**迭代两次*/
    private final int hashIterations = 2;

    /**
     * 加密密码
     * @param user 用户对象
     * */
    public void encryptPassword(User user) {

        user.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }
}
